from sqlalchemy import Column, Integer, String, Text, Boolean, DateTime, ForeignKey
from sqlalchemy.orm import relationship
from datetime import datetime
from database.db import Base


class DetectionModel(Base):
    """检测模型表"""
    __tablename__ = "detection_models"
    
    id = Column(Integer, primary_key=True, index=True, comment="模型ID")
    name = Column(String(200), nullable=False, comment="模型名称")
    description = Column(Text, comment="模型描述")
    format = Column(String(50), nullable=False, comment="模型格式(如YOLOv8、Mask R-CNN)")
    application_scenario = Column(Text, nullable=False, comment="适用场景(如管道泄漏、电力线破损)")
    input_requirements = Column(Text, comment="输入要求(图片/视频分辨率)")
    output_format = Column(Text, comment="输出格式(坐标+置信度)")
    current_version_id = Column(Integer, ForeignKey('model_versions.id'), nullable=True, comment="当前使用的版本ID")
    is_active = Column(Boolean, default=True, comment="是否激活")
    created_at = Column(DateTime, default=datetime.now, comment="创建时间")
    updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now, comment="更新时间")
    
    # 关系
    versions = relationship("ModelVersion", back_populates="model", foreign_keys="ModelVersion.model_id", cascade="all, delete-orphan")
    current_version = relationship("ModelVersion", back_populates="current_for_model", foreign_keys=[current_version_id])


class ModelVersion(Base):
    """模型版本表"""
    __tablename__ = "model_versions"
    
    id = Column(Integer, primary_key=True, index=True, comment="版本ID")
    model_id = Column(Integer, ForeignKey('detection_models.id'), nullable=False, comment="模型ID")
    version_name = Column(String(100), nullable=False, comment="版本名称(如V1.0基础版、V1.1优化版)")
    version_code = Column(String(50), nullable=False, comment="版本号(如1.0.0)")
    file_path = Column(String(500), comment="模型文件路径")
    accuracy = Column(String(50), comment="准确率")
    recall = Column(String(50), comment="召回率")
    description = Column(Text, comment="版本描述")
    is_active = Column(Boolean, default=True, comment="是否激活")
    created_at = Column(DateTime, default=datetime.now, comment="创建时间")
    updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now, comment="更新时间")
    
    # 关系
    model = relationship("DetectionModel", back_populates="versions", foreign_keys=[model_id])
    current_for_model = relationship("DetectionModel", uselist=False, back_populates="current_version", foreign_keys="DetectionModel.current_version_id")